package com.xuduo.amd.service.impl;

import com.auth0.jwt.JWT;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.xuduo.amd.auth.JwtService;
import com.xuduo.amd.dao.EamUserDao;
import com.xuduo.amd.entity.EamUserLoginInfoEntity;
import com.xuduo.amd.service.EamUserLoginInfoService;
import com.xuduo.amd.util.AESUtils;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.scheduling.annotation.Async;

import javax.naming.AuthenticationException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.*;

public class EamServiceImpl implements com.xuduo.amd.service.EamService {
    @Autowired
    private EamUserLoginInfoService eamUserLoginInfoService;

    @Autowired
    private EamUserDao eamUserDao;
    @Autowired
    private JwtService jwtService;
    @Autowired
    @Qualifier("contextSource")
    private LdapContextSource source;

    @Value("${spring.ldap.Urls}")
    private String[] ldapUrls;

    @Value("${spring.ldap.base}")
    private String ldapUserBaseDn;
    @Value("${spring.ldap.ldap-filter}")
    private String ldapFilter;
    //    @Value("${ace.key-password.token.expires}")
//    private long expires;
    @Value("${ace.key-password.secret}")
    private String SECRET;
    public static final List<String> roleList = new ArrayList<>();

    static {
        roleList.add("itw_fdsfdsfds");
        roleList.add("itw_fdsfdfdsfds");
        roleList.add("itw_fdsfdsfds");
        roleList.add("itw_fdsfdsfds");
        roleList.add("itw_fdsfdsfds");
        roleList.add("itw_fdsfdsfds");
        roleList.add("itw_fdsfdsfds");
    }

    private static String state = "true";


    @Override
    public Map<String, Object> login(User user) throws NamingException {


        Map<String, Object> result = new HashMap<>();
        String username = user.getUsername();
        String password = AESUtils.decrypt(SECRET.getBytes(), user.getPassword());
        boolean allowLogin = false;
        SearchControls ctrl = new SearchControls();
        ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] lookupAttr = new String[]{"uid", "cn", "tkorgnamepath", "tkdepartmentid", "tkssovalid"};
        ctrl.setReturningAttributes(lookupAttr);
        StringBuffer buffer = new StringBuffer();
        StringBuffer pri = buffer.append("uid=").append(username).append(".").append(ldapUserBaseDn);
        DirContext context = null;
        String cn = null;
        String companyPath = null;
        try {
            context = source.getContext(pri.toString(), password);
            NamingEnumeration<SearchResult> flag = context.search(ldapUserBaseDn, ldapFilter, new String[]
            (username), ctrl);
            if (flag.hasMore()) {
                SearchResult re = flag.next();
                Attributes attrs = re.getAttributes();
                /**第二步，判断用户状态（true：启用、false：禁用）**/
                Attribute status = attrs.get("tkssovalid");
                Optional<Attribute> opi = Optional.ofNullable(status);
                if (opi.isPresent() && status.get().toString().equalsIgnoreCase(state)) {
                    String uid = attrs.get("uid").toString();
                    String tkorgnamepath = attrs.get("tkorgnamepath").toString();
                    cn = attrs.get("cn").toString();
                    allowLogin = true;
                } else {
                    log.info("认证失败，用户(" + username + ")状态无效.");
                }

            } else {
                log.info("认证失败，用户(" + username + ")不在允许范围内.");
            }

        } catch (AuthenticationException e) {
            throw new UnAuthanException("用户名或密码错误");

        } catch (Exception e) {
            throw new UnAuthanException("认证失败，请确认账号信息是否正确");
        }
        log.info(new Date() + username + "认证成功");
        String token = null;
        if (allowLogin) {
            token = jwtService.generateToken(username, user.getClientId());
            Date date = JWT.decode(token).getExpiresAt();
            saveToken(username, token, date, user.getClientId());
        }
        result.put("token",token);
        result.put("userName",username);
        result.put("flag",allowLogin);
        result.put("cn",cn.substring(4,cn.length()));
        result.put("companyPath",companyPath.substring(15,companyPath.length()));
        log.info(new Date()+":"+username+"登录系统");



        return result;
    }

    @Async
    public  void  saveToken(String username,String token,Date date,String clientId){


    }
    @Async
    public  void  saveLoginfo(String uid,String cn,String tkorgnamepath){
        EamUserLoginInfoEntity entity  = new EamUserLoginInfoEntity();
        entity.setLoginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        String newcn= cn.substring(cn.lastIndexOf(":")+1);
        String newUid=uid.substring(uid.lastIndexOf(":")+1);
        String newtk=tkorgnamepath.substring(tkorgnamepath.lastIndexOf(":")+1);
        entity.setCn(newcn);
        entity.setuId(newUid);
        entity.setTkorgnamepath(newtk);
        if (roleList.contains(newUid)){
            entity.setUserState("1");
        }else {
            entity.setUserState("0");
        }
        try {
            eamUserLoginInfoService.insert(entity);
        }catch (Exception e){
            log.info("信息保存失败 {}",e);
        }

    }
}
